package com.dgz.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/08/20/14:13
 * @Description:
 */
//
public class WordCountStreamDemo {

    public static void main(String[] args) throws Exception {
//        1. 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        2. 读取数据
        DataStreamSource<String> lineDs = env.readTextFile("input/word.txt");
//        3. 处理数据 切分 转换 分组 聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOneDs = lineDs.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
//                    转换为二元组
                    Tuple2<String, Integer> stringIntegerTuple2 = Tuple2.of(word, 1);
//                    通过采集器发送数据
                    collector.collect(stringIntegerTuple2);
                }
            }
        });
//        3.2 分组
        KeyedStream<Tuple2<String, Integer>, String> wordAndOneKeys = wordAndOneDs.keyBy(
                new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                        return stringIntegerTuple2.f0;
                    }
                });
//        3.3 聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = wordAndOneKeys.sum(1);
//        4. 输出数据
        result.print();
//        5. 触发执行
        env.execute();
    }
}
